package api

import (
	"api/config"
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"api/pkg"
	"common/consulinit"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
	pb "user_srv/proto"
)

var (
	address    = config.ServerConfigs.UserSrv.Host + ":" + strconv.Itoa(config.ServerConfigs.UserSrv.Port)
	userServer = flag.String(config.ServerConfigs.UserSrv.Name, address, "The server address")
	userSrv    = handler.NewClient().UserServer(userServer)
)

func RegisterService() {
	consulinit.NewConsulClient("117.27.231.112", 8500).RegisterConsul(config.ServerConfigs.UserSrv.Name, []string{"server"},
		config.ServerConfigs.UserSrv.Port, config.ServerConfigs.UserSrv.Host)
}

func Registers(c *gin.Context) {
	RegisterService()
	var json *request.Register
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Register(c, &pb.RegisterRequest{
		Tel:      json.Tel,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "注册成功", register)
}

func Login(c *gin.Context) {
	RegisterService()
	var json *request.Register
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Login(c, &pb.LoginRequest{
		Tel:      json.Tel,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	tokenHandler, _ := pkg.TokenHandler(strconv.FormatInt(register.Id, 10))
	response.Response(c, 200, "登录成功", tokenHandler)
}
